package spring.cloud.tasks.tasks_manager.tasks_manager.listener;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;
import spring.cloud.tasks.tasks_manager.tasks_manager.node.Node;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.AllotTaskItemService;

@Slf4j
@Setter
@Getter
public class TaskExecutorOnlineOfflineListener extends TreeCacheListener {

    private String taskId;
    private AllotTaskItemService allotTaskItemService;

    public TaskExecutorOnlineOfflineListener(String taskId, AllotTaskItemService allotTaskService) {
        this.taskId = taskId;
        this.allotTaskItemService = allotTaskService;
    }

    @Override
    public void childEvent(TreeCacheEvent.Type type, String path, String nodeData) throws Exception {
        if (isTaskExecutorStatusAddedOrRemoved(type, path)) {
            String executorId = Node.getJobServersExecutorNameByStatusPath(path);
            if (type == Type.NODE_ADDED) {
                allotTaskItemService.taskExecutorOnlineAllotTask(taskId, executorId);
            } else {
                allotTaskItemService.taskExecutorOfflineAllotTask(taskId, executorId);
            }
        }
    }

    private boolean isTaskExecutorStatusAddedOrRemoved(TreeCacheEvent.Type type, String path) {
        return (type == Type.NODE_ADDED || type == Type.NODE_REMOVED) && path.matches(Node.getTaskExecutorStatusNodePathRegex(taskId));
    }

}
